package com.shawn.integeration.log.aspect;

import cn.hutool.core.date.DateUtil;
import com.shawn.integeration.log.annonation.Log;
import com.shawn.integeration.log.service.LogHandleService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 日志切面,负责操作日志记录处理
 *
 * @author: shawn
 * @Date: 2023/12/26 10:42
 * @Version 1.0.0
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
    public static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");
    @Resource
    private LogHandleService logHandleService;

    @Before(value = "@annotation(controllerLog)")
    public void doBefore(JoinPoint jp, Log controllerLog) {
        TIME_THREADLOCAL.set(DateUtil.current());
    }

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonRes")
    public void doAfterReturning(JoinPoint jp, Log controllerLog, Object jsonRes) {
        handleLog(jp, controllerLog, null, jsonRes);
    }

    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint jp, Log controllerLog, Exception e) {
        handleLog(jp, controllerLog, e, null);
    }
    protected void handleLog(final JoinPoint jp, Log controllerLog,
                             Exception e, Object jsonRes) {
        try {
            logHandleService.handle(jp,controllerLog,e,jsonRes);
        } catch (Exception exp) {
            log.error("异常信息:{}", exp.getMessage(),e);
        } finally {
            TIME_THREADLOCAL.remove();
        }
    }
}
